package com.intct.hbase.ddl.namesapce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author gufg
 * @since 2025-08-04 16:43
 */
public class CreateNamespace {
    public static void main(String[] args) throws IOException {
        // 创建HBase连接
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "cdh-node:2181");
        Connection connection = ConnectionFactory.createConnection(conf);

        // 创建一个Admin实例  admin是在DDL操作使用。连接是轻量级、不是线程安全、不建议池化
        Admin admin = connection.getAdmin();

        // 查询所有命名空间
        List<String> listNamespaces = Arrays.asList(admin.listNamespaces());

        String namespace = "intct83_api";

        // 构建一个命名空间描述
        NamespaceDescriptor.Builder builder = NamespaceDescriptor.create(namespace);
        // 设置属性key 和 value
        builder.addConfiguration("intct", "83_api");

        try {
            // 执行创建命名空间
            if (!listNamespaces.contains(namespace)) {
                admin.createNamespace(builder.build());
            } else {
                System.out.println("命名空间已经存在!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (admin != null) {
                admin.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
